package me.zhengjie.modules.mnt.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sun.jna.Pointer;
import me.zhengjie.domain.FhAllDevice;
import me.zhengjie.domain.FhPerRecord;
import me.zhengjie.modules.mnt.websocket.entrance.LoginModule;
import me.zhengjie.modules.mnt.websocket.entrance.NetSDKLib;
import me.zhengjie.modules.mnt.websocket.entrance.ToolKits;
import me.zhengjie.service.FhDeviceService;
import me.zhengjie.service.FhPerRecordService;
import me.zhengjie.service.dto.FhDeviceDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
public class AisThread implements Runnable{

    @Autowired
    FhDeviceService aisDayService;

    @Autowired
    FhPerRecordService fhPerRecordService;

    private List<LoginModule> realLoadPicArray = new ArrayList<LoginModule>();

    private String timer = new Date().toString();

    private static AisThread  aisThread ;

    private CopyOnWriteArraySet<WebSocketServer> socketServerSet = null;

    @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {
        aisThread = this;
        aisThread.aisDayService = this.aisDayService;
        aisThread.fhPerRecordService = this.fhPerRecordService;
        aisThread.realLoadPicArray = this.realLoadPicArray;
        aisThread.timer = this.timer;
        // 初使化时将已静态化的testService实例化
    }
    boolean stopMe = true;
    public void stopMe() {
        stopMe = false;
    }
    public void subscriberDevice(String message) {
//        Object object = JSONObject.toJSON(message);
//        LoginModule.init(null,null);
//        Student[] students = new Gson().fromJson(jsonString, Student[].class)
//        for (Object fhAllDevice:(List)object ) {
//            System.out.println(fhAllDevice);
//            System.out.println(111);
//        }
//        FhAllDevice jsonArray = JSONArray.parseObject(message, FhAllDevice.class);
//        System.out.println(jsonArray);
        socketServerSet = WebSocketServer.getWebSocketSet();
        System.out.println("__________________________________________________________________________________________________");
        System.out.println(aisThread.realLoadPicArray.size());
        for (LoginModule loginModule:aisThread.realLoadPicArray ) {
            loginModule.stopRealLoadPic(loginModule.m_hLoginHandle);
            loginModule.logout();
        }
        System.out.println("__________________________________________________________________________________________________");
        aisThread.realLoadPicArray.clear();
//        LoginModule.init(null,null);

        List<FhAllDevice> jacksonList = (List<FhAllDevice>) JSON.parseArray(message, FhAllDevice.class);
        for (FhAllDevice fhAllDevice : jacksonList) {
            LoginModule loginModule = new LoginModule();
            loginModule.init(null,null);
            Boolean is = loginModule.login(fhAllDevice.getIp(),fhAllDevice.getPort(),fhAllDevice.getUserName(),fhAllDevice.getPassWord());
            if(is){
                loginModule.realLoadPic(0,new AnalyzerDataCB());
                aisThread.realLoadPicArray.add(loginModule);
            }
            for (WebSocketServer item : socketServerSet) {
			try {
			    if(!is)item.sendMessage(fhAllDevice.getName()+"登录失败");
			} catch (IOException e) {
			}
		}

//
//            Boolean is = LoginModule.login(fhAllDevice.getIp(),fhAllDevice.getPort(),fhAllDevice.getUserName(),fhAllDevice.getPassWord());
//            if(!is){
//                try {
//                    socketServer.onMessage(fhAllDevice.getIp()+"登录失败");
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                break;
//            }else {
//                LoginModule.realLoadPic(0,new AnalyzerDataCB());
//            }
        }
    }

    @Override
    public void run() {
        WebSocketServer webSocketServer = new WebSocketServer();

//        while (stopMe){
//            try {
//                FhDeviceDto aisJkxxbDays = aisThread.aisDayService.findById(4);
//                String message = JSONObject.toJSONString(aisJkxxbDays);
//                webSocketServer.onMessage(message);
//                Thread.sleep(2000);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
    }

    private class AnalyzerDataCB implements NetSDKLib.fAnalyzerDataCallBack {
        private BufferedImage gateBufferedImage = null;


        @Override
        public int invoke(NetSDKLib.LLong lAnalyzerHandle, int dwAlarmType,
                          Pointer pAlarmInfo, Pointer pBuffer, int dwBufSize,
                          Pointer dwUser, int nSequence, Pointer reserved)
        {

            if (lAnalyzerHandle.longValue() == 0 || pAlarmInfo == null) {
                return -1;
            }

            File path = new File("./GateSnapPicture/");
            if (!path.exists()) {
                path.mkdir();
            }
            ///< 门禁事件
            if(dwAlarmType == NetSDKLib.EVENT_IVS_ACCESS_CTL) {
                NetSDKLib.DEV_EVENT_ACCESS_CTL_INFO msg = new NetSDKLib.DEV_EVENT_ACCESS_CTL_INFO();
                ToolKits.GetPointerData(pAlarmInfo, msg);

                // 保存图片，获取图片缓存
                String snapPicPath = path + "\\" + System.currentTimeMillis() + "GateSnapPicture.jpg";  // 保存图片地址
                byte[] buffer = pBuffer.getByteArray(0, dwBufSize);
                ByteArrayInputStream byteArrInputGlobal = new ByteArrayInputStream(buffer);

                try {
                    gateBufferedImage = ImageIO.read(byteArrInputGlobal);
                    if(gateBufferedImage != null) {
                        ImageIO.write(gateBufferedImage, "jpg", new File(snapPicPath));
                    }
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
                if(!aisThread.timer.equals(msg.UTC.toString())){
                    FhPerRecord fhPerRecord = new FhPerRecord();
                    fhPerRecord.setUserId(new String(msg.szUserID).trim());
                    fhPerRecord.setUserName(new String(msg.szCardName).trim());
                    fhPerRecord.setMethod(msg.emOpenMethod);
                    fhPerRecord.setStatus(msg.bStatus);
                    fhPerRecord.setCardCount(new String(msg.szCardNo).trim());
                    fhPerRecord.setImg(snapPicPath);
                    fhPerRecord.setTime(msg.UTC.toString());
//                fhPerRecord.setDeviceName(new String (msg.szSN ));
                    aisThread.fhPerRecordService.create(fhPerRecord);
                    timer = msg.UTC.toString();
//                socketServerSet = WebSocketServer.getWebSocketSet();
                    for (WebSocketServer item : socketServerSet) {
                        try {
                            item.sendMessage(JSON.toJSONString(fhPerRecord));
                        } catch (IOException e) {
                        }
                    }
                    System.out.println(JSON.toJSONString(fhPerRecord));
                }

                // 图片以及门禁信息界面显示
//                EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
//                if (eventQueue != null) {
//                    eventQueue.postEvent( new AccessEvent(target,
//                            gateBufferedImage,
//                            msg));
//                }
            }

            return 0;
        }
    }
}
